package com.security.uaa.service;

import com.security.uaa.dao.UserDao;
import com.security.uaa.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author wangning
 * @create 2021-03-17 20:52
 * @description
 */
@Service
public class SpringDataUserDetailService implements UserDetailsService {
	@Autowired
	private UserDao userDao;

	//根据账号查询用户信息
//	@Override
//	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//		//将来连接数据库根据账号查询用户
//		//暂时采用模拟方式
//		System.out.println("username = " + username);
//		UserDto user = userDao.getUserByName(username);
//		if (user == null) {
//			return null;
//		}
//		UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities("p1").build();
//
//		return userDetails;
//	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//登录账号
		System.out.println("username=" + username);
		// 根据账号去数据库查询...
		UserDto user = userDao.getUserByName(username);
		if (user == null) {
			return null;
		}
		//查询用户权限
		List<String> permissions = userDao.findPermissionsByUserId(user.getId());
		String[] perarray = new String[permissions.size()];
		permissions.toArray(perarray);
		//创建userDetails
		UserDetails userDetails = User.withUsername(user.getFullname()).password(user.getPassword()).authorities(perarray).build();
		return userDetails;
	}
}
